package com.baihan.angus.app.game.busshow.ui.script_library.online_exhibition.room;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.baihan.angus.app.game.basic.base.BaseResponse;
import com.baihan.angus.app.game.basic.utils.Loog;
import com.baihan.angus.app.game.basic.utils.Tooast;
import com.baihan.angus.app.game.basic.utils.net.RetrofitHelper;
import com.baihan.angus.app.game.busshow.R;
import com.baihan.angus.app.game.busshow.pop_dialog.AppDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.ClueDetailDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.DmManualDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.DmRoleScriptDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.DmScriptDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.GameSettingDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.InviteDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.MapDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.RoleScriptDetailDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.SceneRenderDialog;
import com.baihan.angus.app.game.busshow.pop_dialog.SelectRoleDialog;
import com.baihan.angus.app.game.common.bean.entity.ClueEntity;
import com.baihan.angus.app.game.common.bean.entity.MapEntity;
import com.baihan.angus.app.game.common.bean.response.DmClueResponse;
import com.baihan.angus.app.game.common.bean.response.DmManualResponse;
import com.baihan.angus.app.game.common.bean.response.DmMapResponse;
import com.baihan.angus.app.game.common.bean.response.DmPropsResponse;
import com.baihan.angus.app.game.common.bean.response.DmRoleScriptResponse;
import com.baihan.angus.app.game.common.bean.response.DmScriptResponse;
import com.baihan.angus.app.game.common.bean.response.ManualMenuResponse;
import com.baihan.angus.app.game.common.bean.response.MemberEntity;
import com.baihan.angus.app.game.common.bean.response.MsgEntity;
import com.baihan.angus.app.game.common.bean.response.RoomDetailResponse;
import com.baihan.angus.app.game.common.bean.response.SceneRenderResponse;
import com.baihan.angus.app.game.common.bean.response.ScriptRole;
import com.baihan.angus.app.game.common.configs.UserConfig;
import com.baihan.angus.app.game.common.data_center.remote.api.RoomServer;
import com.baihan.angus.app.game.common.data_center.remote.api.ScriptServer;
import com.baihan.angus.app.game.common.model.TRTCVoiceRoomCallback;
import com.baihan.angus.app.game.common.model.TRTCVoiceRoomDef;
import com.baihan.angus.app.game.common.model.VoiceRoomManager;
import com.baihan.angus.app.game.common.util.media.DefMediaInfo;
import com.baihan.angus.app.game.common.util.media.IMediaInfo;
import com.baihan.angus.app.game.common.util.media.MediaGalleryActivity;
import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.PermissionUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.tencent.liteav.audio.TXAudioEffectManager;
import com.tencent.trtc.TRTCCloudDef;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_CANCEL_READY;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_DM_CHANGE_BG;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_DM_CHANGE_MUSIC;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_DM_CHOOSE_MVP;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_DM_SEND_BOOK;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_DM_SEND_MAP;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_DM_SEND_PROP;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_DM_SEND_THREAD;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_GAME_START;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_PLAYER_READ_FINISH;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_PLAYER_TRANSFER_PROP;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_PLAYER_USE_PROP;
import static com.baihan.angus.app.game.common.constants.BasicConstants.MSG_READY;

/**
 * DM创建房间
 */
@RequiresApi(api = Build.VERSION_CODES.N)
public class VoiceRoomDmActivity extends VoiceRoomBaseActivity {
    public static final int ERROR_ROOM_ID_EXIT = -1301;

    // 用户申请上麦的map
    private Map<String, String> mTakeSeatInvitationMap;
    // 邀请人上麦的map
    private Map<String, SeatInvitation> mPickSeatInvitationMap;
    private boolean mIsEnterRoom;

    private AppDialog mAppDialog;
    private InviteDialog mInviteDialog;
    private GameSettingDialog mGameSettingDialog;
    private DmManualDialog mDmManualDialog;
    private DmScriptDialog mDmScriptDialog;
    private DmRoleScriptDialog mDmRoleScriptDialog;
    private RoleScriptDetailDialog mRoleScriptDetailDialog;
    private SceneRenderDialog mSceneRenderDialog;
    private SelectRoleDialog mSelectRoleDialog;
    private ClueDetailDialog mClueDetailDialog;
    private MapDialog mMapDialog;

    private BGMListener mBGMPlayListenr;
    private ManualMenuResponse.Data menuData;
    private List<DmManualResponse.DataX> manualList;
    private List<DmScriptResponse.DataXX> scriptList;
    private List<DmClueResponse.DataX> clueList;
    private List<DmPropsResponse.DataX> propsList;
    private List<DmMapResponse.DataX> mapList;
    private DmRoleScriptResponse.DataXX roleScriptData;
    private SceneRenderResponse.DataX sceneRenderData;

    private Map<String, Object> mSendClueRequest = new HashMap<>();
    private Map<String, Object> mOpenClueRequest = new HashMap<>();
    private Map<String, Object> mSendPropRequest = new HashMap<>();
    private Map<String, Object> mSendMapRequest = new HashMap<>();
    private Map<String, Object> mChooseMvpRequest = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initDM();
        initClick();
    }

    /**
     * 创建房间
     */
    public static void createRoom(Context context, RoomDetailResponse.Data roomDetail, String roomId, String roomName,
                                  int seatCount, String userId, String userName, String coverUrl,
                                  int audioQuality, boolean needRequest) {
        Intent intent = new Intent(context, VoiceRoomDmActivity.class);
        intent.putExtra(ROOM_DETAIL, roomDetail);
        intent.putExtra(VOICEROOM_ROOM_ID, roomId);
        intent.putExtra(VOICEROOM_ROOM_NAME, roomName);
        intent.putExtra(VOICEROOM_SEAT_COUNT, seatCount);
        intent.putExtra(VOICEROOM_USER_ID, userId);
        intent.putExtra(VOICEROOM_USER_NAME, userName);
        intent.putExtra(VOICEROOM_AUDIO_QUALITY, audioQuality);
        intent.putExtra(VOICEROOM_ROOM_COVER, coverUrl);
        intent.putExtra(VOICEROOM_NEED_REQUEST, needRequest);
        context.startActivity(intent);
    }

    /**
     * DM的逻辑
     */
    private void initDM() {
        mTakeSeatInvitationMap = new HashMap<>();
        mPickSeatInvitationMap = new HashMap<>();
        mVoiceRoomSeatAdp.notifyDataSetChanged();
//        mViewSelectMember.setList(mMemberEntityList);
//        mViewSelectMember.setOnSelectedCallback(this);
        //刷新界面的按钮
        ibMicro.setActivated(true);
        ibVolume.setActivated(true);
        ibVoice.setActivated(true);
        ibDmVoice.setActivated(true);
        ibGameVolume.setActivated(true);
//        mBtnEffect.setVisibility(View.VISIBLE);
//        btnSaySome.setActivated(true);
//
//        btnSaySome.setSelected(true);
        ibMicro.setSelected(true);
        ibVolume.setSelected(true);
        ibVoice.setSelected(true);
        ibDmVoice.setSelected(true);
        ibGameVolume.setSelected(true);
//        mBtnEffect.setSelected(true);

        mCurrentRole = TRTCCloudDef.TRTCRoleAnchor;
        //设置昵称、头像
        mTRTCVoiceRoom.setSelfProfile(mUserName, mUserAvatar, null);
        PermissionUtils.permission(PermissionConstants.MICROPHONE).callback(new PermissionUtils.FullCallback() {
            @Override
            public void onGranted(List<String> permissionsGranted) {
                internalCreateRoom();
            }

            @Override
            public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {
                Tooast.normalInfo(getString(R.string.trtcvoiceroom_tips_open_audio));
            }
        }).request();

        //初始化bgm监听
        mBGMPlayListenr = new BGMListener();

        //获取DM手册目录
        getDmMenu(mRoomDetail.getScript_id(), "manual", mRoomId);
        getDmMenuDetail(mRoomDetail.getScript_id(), "manual", "manual", mRoomId);
        getDmScriptDetail(mRoomDetail.getScript_id(), "manual", "script", mRoomId);
        getDmClueDetail(mRoomDetail.getScript_id(), "manual", "clue", mRoomId);
        getDmPropsDetail(mRoomDetail.getScript_id(), "manual", "prop", mRoomId);
        getDmMapDetail(mRoomDetail.getScript_id(), "manual", "map", mRoomId);

        //获取角色剧本
        getDmRoleScript(mRoomDetail.getScript_id(), "script");

        //获取情景渲染数据
        getSceneRender(mRoomDetail.getScript_id(), "scene");
    }

    public void initClick() {

        tvReady.setOnClickListener(view -> {
//            for (int i = 0; i < mVoiceRoomSeatEntityList.size(); i++) {
//                //暂时先做一个玩家的判断
//                if (!mVoiceRoomSeatEntityList.get(i).isReady) {
//                    Tooast.normalInfo("玩家尚未准备");
//                    break;
//                } else {
            llRoom.setVisibility(View.GONE);
            llGame.setVisibility(View.VISIBLE);
            llDMTab.setVisibility(View.VISIBLE);
            llPlayeTab.setVisibility(View.GONE);

            sendCustomGameStartMsg();
//                }
//            }
        });

        tvInvite.setOnClickListener(view -> {
            showInviteDialog();
        });

        llSetting.setOnClickListener(view -> {
            showGameSettingDialog();
        });

        ivDmMenu.setOnClickListener(v -> {
            showManualDialog();
        });

        ivRoleScript.setOnClickListener(v -> {
            showDmRoleScriptDialog();
        });

        ivRecord.setOnClickListener(v -> {

        });

        ivSceneRender.setOnClickListener(v -> {
            showSceneRenderDialog();
        });

        ivMVP.setOnClickListener(v -> {
            //此处参数不重要
            showSelectRoleDialog(2, -1, "");
        });
    }

    //发送游戏开始消息
    public void sendCustomGameStartMsg() {
        mTRTCVoiceRoom.sendRoomCustomMsg(MSG_GAME_START, "", new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    //获取第一幕剧情(根据mRoomDetail.getScript_step()来判断有几幕)
//                    getScriptStepDetail(mRoomDetail.getScript_id(), currentStep, mRoomId);
                }
            }
        });
    }

    //DM发送剧本
    private void sendCustomScriptMsg(int position, String scriptId) {
        mTRTCVoiceRoom.sendRoomCustomMsg(MSG_DM_SEND_BOOK, scriptId, new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    mDmManualDialog.refreshScript(position);
                    Tooast.normalInfo("发送剧本成功");
                }
            }
        });
    }

    //DM发送线索
    private void sendCustomClueMsg(String sendType, int position, String clueId) {
        mTRTCVoiceRoom.sendRoomCustomMsg(MSG_DM_SEND_THREAD, clueId, new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    if (sendType.equals("send")) {
                        mDmManualDialog.refreshClueSend(position);
                        Tooast.normalInfo("发送线索成功");
                    } else if (sendType.equals("open")) {
                        //公开即发送给每个玩家
                        mDmManualDialog.refreshClueSend(position);
                        mDmManualDialog.refreshClueOpen(position);
                        Tooast.normalInfo("公开线索成功");
                    }
                }
            }
        });
    }

    //DM发送道具
    private void sendCustomPropMsg(int position, String propId, String roleName) {
        mTRTCVoiceRoom.sendRoomCustomMsg(MSG_DM_SEND_PROP, propId, new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    mDmManualDialog.refreshPropSend(position, roleName);
                    Tooast.normalInfo("发送道具成功");
                }
            }
        });
    }

    //DM发送地图
    private void sendCustomMapMsg(int position, String mapId) {
        mTRTCVoiceRoom.sendRoomCustomMsg(MSG_DM_SEND_MAP, mapId, new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    mDmManualDialog.refreshMapSend(position);
                    Tooast.normalInfo("发送地图成功");
                }
            }
        });
    }

    //DM选择mvp
    private void sendCustomMvpMsg(int position, String roleId) {
        mTRTCVoiceRoom.sendRoomCustomMsg(MSG_DM_CHOOSE_MVP, roleId, new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    Tooast.normalInfo("选择mvp成功");
                }
            }
        });
    }

    //DM切换背景
    private void sendChangeBgMsg(String bgUrl) {
        mTRTCVoiceRoom.sendRoomCustomMsg(MSG_DM_CHANGE_BG, bgUrl, new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    Tooast.normalInfo("切换背景图片成功");
                }
            }
        });
    }

    //DM切换背景音乐
    private void sendChangeMusicMsg(String scriptId) {
        mTRTCVoiceRoom.sendRoomCustomMsg(MSG_DM_CHANGE_MUSIC, scriptId, new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    Tooast.normalInfo("切换背景音乐成功");
                }
            }
        });
    }

    private void showGameSettingDialog() {
        if (null == mGameSettingDialog) {
            mGameSettingDialog = new GameSettingDialog(this, new GameSettingDialog.Callback() {
                @Override
                public void onInitiateDissolution() {

                }

                @Override
                public void onShareRoom() {

                }

                @Override
                public void onExitGame() {
                    onBackPressed();
                }
            });
        }
        mGameSettingDialog.setAudioEffectManager(mAudioEffectManager);
        mGameSettingDialog.setBgmId(bgmId);
        mGameSettingDialog.show();
    }

    //展示主持人手册Dialog
    private void showManualDialog() {
        if (null == mDmManualDialog) {
            mDmManualDialog = new DmManualDialog(this, new DmManualDialog.Callback() {
                @Override
                public void onShowDetail(int position, List<DmManualResponse.DataX.Data> data) {
                    showDmScriptDialog(position, data);
                }

                @Override
                public void onSendScript(int position, String scriptId) {
                    sendCustomScriptMsg(position, scriptId);
                }

                @Override
                public void onSendClue(int position, String clueId) {
                    mSendClueRequest.put("room_sn", mRoomId);
                    mSendClueRequest.put("clue_id", clueId);
                    mSendClueRequest.put("action", "send");
                    mSendClueRequest.put("user", "dm");
                    showSelectRoleDialog(0, position, clueId);
                }

                @Override
                public void onOpenClue(int position, String clueId) {
                    mOpenClueRequest.put("room_sn", mRoomId);
                    mOpenClueRequest.put("clue_id", clueId);
                    mOpenClueRequest.put("action", "open");
                    mOpenClueRequest.put("user", "dm");
                    sendClue(position, mRoomDetail.getScript_id(), mOpenClueRequest, clueId, "open");
                }

                @Override
                public void onShowClueDetail(int position, ClueEntity clueData) {
                    showClueDetailDialog(position, clueData);
                }

                @Override
                public void onSendProps(int position, String propId) {
                    mSendPropRequest.put("room_sn", mRoomId);
                    mSendPropRequest.put("prop_id", propId);
                    mSendPropRequest.put("action", "send");
                    showSelectRoleDialog(1, position, propId);
                }

                @Override
                public void onShowMap(int position, String mapId) {
                    mSendMapRequest.put("room_sn", mRoomId);
                    mSendMapRequest.put("map_id", mapId);
                    mSendMapRequest.put("action", "open");
                    sendMap(position, mRoomDetail.getScript_id(), mSendMapRequest, mapId);
                }

                @Override
                public void onShowMapDetail(int position, MapEntity mapData) {
                    List<IMediaInfo> iMediaInfos = new ArrayList<>();
                    iMediaInfos.add(new DefMediaInfo(mapData.getUrl().get(0).getUrl()));
                    MediaGalleryActivity.start(VoiceRoomDmActivity.this, iMediaInfos, 0, 1);
                }
            });
        }
        mDmManualDialog.initData(menuData, manualList, scriptList, clueList, propsList, mapList);
        mDmManualDialog.show();
    }

    //线索详情
    private void showClueDetailDialog(int position, ClueEntity clueData) {
        mClueDetailDialog = new ClueDetailDialog(VoiceRoomDmActivity.this, new ClueDetailDialog.Callback() {
            @Override
            public void onDisclose(String clueId) {
            }

            @Override
            public void onOpen(String clueId) {
            }
        });
        mClueDetailDialog.initClueData(clueData, "dm");
        mClueDetailDialog.show();
    }

    //展示DM查看剧本目录
    private void showDmScriptDialog(int selectPos, List<DmManualResponse.DataX.Data> data) {
        if (null == mDmScriptDialog) {
            mDmScriptDialog = new DmScriptDialog(this);
        }
        mDmScriptDialog.initData(selectPos, data);
        mDmScriptDialog.show();
    }

    //展示DM查看角色剧本
    private void showDmRoleScriptDialog() {
        if (null == mDmRoleScriptDialog) {
            mDmRoleScriptDialog = new DmRoleScriptDialog(this, new DmRoleScriptDialog.Callback() {
                @Override
                public void onShowDetail(List<DmRoleScriptResponse.DataXX.ScriptData.DataX.Data> data) {
                    showRoleScriptDetailDialog(data);
                }
            });
        }
        mDmRoleScriptDialog.initData(roleScriptData);
        mDmRoleScriptDialog.show();
    }

    //查看角色剧本详情
    private void showRoleScriptDetailDialog(List<DmRoleScriptResponse.DataXX.ScriptData.DataX.Data> data) {
        if (null == mRoleScriptDetailDialog) {
            mRoleScriptDetailDialog = new RoleScriptDetailDialog(this);
        }
        mRoleScriptDetailDialog.initData(data);
        mRoleScriptDetailDialog.show();
    }

    //查看情景渲染dialog
    private void showSceneRenderDialog() {
        if (null == mSceneRenderDialog) {
            mSceneRenderDialog = new SceneRenderDialog(this, new SceneRenderDialog.Callback() {
                @Override
                public void play(SceneRenderResponse.DataX.SceneData.Data data) {
                    //资源类型 0图片 1文本 2音乐 3视频
                    if (data.getRes_type() == 0) {
                        changeDmBg(data);
                    } else if (data.getRes_type() == 2) {
                        changeDmMusic(data);
                    } else if (data.getRes_type() == 3) {

                    }
                }
            });
        }
        mSceneRenderDialog.initData(sceneRenderData);
        mSceneRenderDialog.show();
    }

    //选择角色
    private void showSelectRoleDialog(int type, int position, String id) {
        mSelectRoleDialog = new SelectRoleDialog(this, new SelectRoleDialog.Callback() {
            @Override
            public void send(int type, String roleId, String roleName) {
                if (type == 0) {//0-发线索 1-发道具 2-选择MVP
                    mSendClueRequest.put("script_role_id", roleId);
                    sendClue(position, mRoomDetail.getScript_id(), mSendClueRequest, id, "send");
                    mSelectRoleDialog.dismiss();
                } else if (type == 1) {
                    mSendPropRequest.put("script_role_id", roleId);
                    sendProp(position, mRoomDetail.getScript_id(), mSendPropRequest, id, roleName);
                    mSelectRoleDialog.dismiss();
                } else if (type == 2) {
                    mChooseMvpRequest.put("script_role_id", roleId);
                    mChooseMvpRequest.put("user_id", UserConfig.getUserConfig().getUser().getUser_id());
                    chooseMvp(position, roleId, mChooseMvpRequest);
                    mSelectRoleDialog.dismiss();
                }
            }
        });
        mSelectRoleDialog.initData(type, mRoomDetail.getScript_role());
        mSelectRoleDialog.show();
    }

    //切换场景背景图片
    private void changeDmBg(SceneRenderResponse.DataX.SceneData.Data data) {
        Glide.with(this).asBitmap().load(data.getUrl().get(0).getUrl())
                .transition(BitmapTransitionOptions.withCrossFade(1000)).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                Drawable drawable = new BitmapDrawable(resource);
                llGame.setBackground(drawable);
                mSceneRenderDialog.dismiss();
            }
        });
        //通知玩家端切换背景图片
        sendChangeBgMsg(data.getUrl().get(0).getUrl());
    }

    //切换场景背景音乐
    private void changeDmMusic(SceneRenderResponse.DataX.SceneData.Data data) {
        //播放bgm
        if (null != data.getUrl()) {
            if (bgmId != -1) { // 已开始播放音乐，需要先停止上一次正在播放的音乐
                mAudioEffectManager.stopPlayMusic(bgmId);
            }
            bgmId = Integer.parseInt(data.getUrl().get(0).getId());
            bgmUrl = data.getUrl().get(0).getUrl();
            audioMusicParam = new TXAudioEffectManager.AudioMusicParam(bgmId, bgmUrl);
            mAudioEffectManager.setMusicObserver(bgmId, mBGMPlayListenr);

            //设置bgm初始音量为50
            mAudioEffectManager.setMusicPlayoutVolume(bgmId, 50);
            mAudioEffectManager.setMusicPublishVolume(bgmId, 50);

            mAudioEffectManager.startPlayMusic(audioMusicParam);

            mSceneRenderDialog.dismiss();

            //通知玩家端切换背景音乐
            sendChangeMusicMsg(data.getUrl().get(0).getId() + "," + data.getUrl().get(0).getUrl());
        }
    }

    private void onCloseSeatClick(int itemPos) {
        ScriptRole entity = mVoiceRoomSeatEntityList.get(itemPos);
        if (entity == null) {
            return;
        }
        final boolean isClose = entity.isClose;
//        mTRTCVoiceRoom.closeSeat(changeSeatIndexToModelIndex(itemPos), !isClose, new TRTCVoiceRoomCallback.ActionCallback() {
//            @Override
//            public void onCallback(int code, String msg) {
//                if (code == 0) {
//                    mViewSelectMember.updateCloseStatus(!isClose);
//                }
//            }
//        });
    }

    private void internalCreateRoom() {
        final TRTCVoiceRoomDef.RoomParam roomParam = new TRTCVoiceRoomDef.RoomParam();
        roomParam.roomName = mRoomName;
        roomParam.needRequest = mNeedRequest;
        roomParam.seatCount = mSeatCount;
        roomParam.coverUrl = mRoomCover;
        mTRTCVoiceRoom.createRoom(mRoomId, roomParam, new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    onTRTCRoomCreateSuccess();
                } else {
                    Loog.dTag("CreateRoom", "roomId = " + mRoomId + ",roomParam = " + new Gson().toJson(roomParam));
                    Loog.dTag("CreateRoom", "Error code : " + code + ",msg : " + msg);
                }
            }
        });
    }

    private void onTRTCRoomCreateSuccess() {
        mIsEnterRoom = true;
        tvRoomName.setText(mRoomName);
        tvRoomId.setText("ID:" + mRoomId);
        mTRTCVoiceRoom.setAudioQuality(mAudioQuality);
        takeMainSeat();
        VoiceRoomManager.getInstance().createRoom(mRoomId, new VoiceRoomManager.ActionCallback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onError(int errorCode, String message) {
                if (errorCode == ERROR_ROOM_ID_EXIT) {
                    onSuccess();
                } else {
                    Loog.dTag("Reason:;", "失败 " + errorCode + ", " + message);
                    finish();
                }
            }
        });
    }

    private void takeMainSeat() {
        // 开始创建房间
        mTRTCVoiceRoom.enterSeat(0, new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    //成功上座位，可以展示UI了
                    Tooast.normalInfo(getString(R.string.trtcvoiceroom_toast_owner_succeeded_in_occupying_the_seat));
                } else {
                    Tooast.normalInfo(getString(R.string.trtcvoiceroom_toast_owner_failed_to_occupy_the_seat) + "[" + code + "]:" + msg);
                }
            }
        });
    }

    @Override
    public void onAudienceEnter(TRTCVoiceRoomDef.UserInfo userInfo) {
        super.onAudienceEnter(userInfo);
        if (userInfo.userId.equals(mSelfUserId)) {
            return;
        }
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.userId = userInfo.userId;
        memberEntity.userAvatar = userInfo.userAvatar;
        memberEntity.userName = userInfo.userName;
        memberEntity.type = MemberEntity.TYPE_IDEL;
        if (!mMemberEntityMap.containsKey(memberEntity.userId)) {
            mMemberEntityMap.put(memberEntity.userId, memberEntity);
            mMemberEntityList.add(memberEntity);
        }
        Loog.dTag("RoomUserInfo", "enter info : " + new Gson().toJson(userInfo));
//        tvWaitingNum.setText(mMemberEntityList.size() + "人");
//        if (mViewSelectMember != null) {
//            mViewSelectMember.notifyDataSetChanged();
//        }
    }

    @Override
    public void onAudienceExit(TRTCVoiceRoomDef.UserInfo userInfo) {
        super.onAudienceExit(userInfo);
        MemberEntity entity = mMemberEntityMap.remove(userInfo.userId);
        if (entity != null) {
            mMemberEntityList.remove(entity);
            mMemberEntityMap.remove(userInfo.userId);
        }
//        tvWaitingNum.setText(mMemberEntityList.size() + "人");
//        if (mViewSelectMember != null) {
//            mViewSelectMember.notifyDataSetChanged();
//        }
    }

    @Override
    public void onAnchorEnterSeat(int index, TRTCVoiceRoomDef.UserInfo user) {
        super.onAnchorEnterSeat(index, user);
        MemberEntity entity = mMemberEntityMap.get(user.userId);
        Loog.dTag("RoomUserInfo", "choose info : " + new Gson().toJson(user));
        if (entity != null) {
            entity.type = MemberEntity.TYPE_IN_SEAT;
        }
//        if (mViewSelectMember != null) {
//            mViewSelectMember.notifyDataSetChanged();
//        }
    }

    @Override
    public void onAnchorLeaveSeat(int index, TRTCVoiceRoomDef.UserInfo user) {
        super.onAnchorLeaveSeat(index, user);
        MemberEntity entity = mMemberEntityMap.get(user.userId);
        if (entity != null) {
            entity.type = MemberEntity.TYPE_IDEL;
        }
//        if (mViewSelectMember != null) {
//            mViewSelectMember.notifyDataSetChanged();
//        }
    }

    @Override
    public void onVoice(int position) {
        // 判断座位有没有人
        ScriptRole entity = mVoiceRoomSeatEntityList.get(position);
        if (entity.isUsed) {
            // 有人禁言
            final boolean isMute = entity.isSeatMute;
            mTRTCVoiceRoom.muteSeat(changeSeatIndexToModelIndex(position), !isMute, null);
        }
    }

    @Override
    public void onVoiceMute(int position) {
        // 判断座位有没有人
        ScriptRole entity = mVoiceRoomSeatEntityList.get(position);
        if (entity.isUsed) {
            // 有人禁言
            final boolean isMute = entity.isSeatMute;
            mTRTCVoiceRoom.muteSeat(changeSeatIndexToModelIndex(position), !isMute, null);
        }
    }

    //禁言/取消禁言所有人
    public void muteAll(boolean isMute) {
        for (int i = 0; i < mVoiceRoomSeatEntityList.size(); i++) {
            ScriptRole entity = mVoiceRoomSeatEntityList.get(i);
            if (entity.isUsed) {
                // 有人禁言
                mTRTCVoiceRoom.muteSeat(changeSeatIndexToModelIndex(i), isMute, null);
            }
        }
    }

    @Override
    public void onRecvRoomCustomMsg(String cmd, String message, TRTCVoiceRoomDef.UserInfo userInfo) {
        super.onRecvRoomCustomMsg(cmd, message, userInfo);
        MsgEntity msgEntity = new MsgEntity();
        msgEntity.userId = userInfo.userId;
        msgEntity.userName = userInfo.userName;
        msgEntity.type = MsgEntity.TYPE_NORMAL;
        if (cmd.equals(MSG_READY)) {//玩家准备
            int index = Integer.parseInt(message);
            msgEntity.content = getString(R.string.trtcvoiceroom_tv_ready, "");
            mVoiceRoomSeatEntityList.get(index).isReady = true;
            mVoiceRoomSeatAdp.notifyDataSetChanged();
            showImMsg(msgEntity);
        } else if (cmd.equals(MSG_CANCEL_READY)) {//玩家取消准备
            int index = Integer.parseInt(message);
            mVoiceRoomSeatEntityList.get(index).isReady = false;
            mVoiceRoomSeatAdp.notifyDataSetChanged();
            msgEntity.content = getString(R.string.trtcvoiceroom_tv_cancel_ready, "");
            showImMsg(msgEntity);
        } else if (cmd.equals(MSG_PLAYER_READ_FINISH)) {//玩家阅读剧本完成
            int index = Integer.parseInt(message);
            mVoiceRoomSeatEntityList.get(index).isComplete = true;
            mGameSeatAdp.notifyDataSetChanged();
//            msgEntity.content = getString(R.string.trtcvoiceroom_tv_complete, "");
        } else if (cmd.equals(MSG_PLAYER_TRANSFER_PROP)) {//玩家转交道具
            //重新获取道具列表信息
            getDmPropsDetail(mRoomDetail.getScript_id(), "manual", "prop", mRoomId);
        } else if (cmd.equals(MSG_PLAYER_USE_PROP)) {//玩家使用道具
            //重新获取道具列表信息
            getDmPropsDetail(mRoomDetail.getScript_id(), "manual", "prop", mRoomId);
        }
    }

    @Override
    public void onBackPressed() {
        dissolutionRoom();
    }

    private void dissolutionRoom() {
        if (null == mAppDialog) {
            mAppDialog = new AppDialog(this, new AppDialog.Callback() {
                @Override
                public void onDetermine() {
//                    mTRTCVoiceRoom.setDelegate(null);
                    dissolution();
                }
            });
        }
        mAppDialog.setMessage(getString(R.string.dissolutionRoom));
        mAppDialog.setDetermine(getString(R.string.determine));
//        mAppDialog.setDetermineColor(getColor(R.color.textColor15));
        mAppDialog.setCancel(getString(R.string.cancel));
        mAppDialog.setCancelPic(getDrawable(R.mipmap.ic_cancel));
        mAppDialog.setDeterminePic(getDrawable(R.mipmap.ic_right));
        mAppDialog.show();
    }

    private void showInviteDialog() {
        if (null == mInviteDialog) {
            mInviteDialog = new InviteDialog(this, new InviteDialog.Callback() {
                @Override
                public void onWechat() {
                    mInviteDialog.dismiss();
                }

                @Override
                public void onQQ() {
                    mInviteDialog.dismiss();
                }
            });
        }
        mInviteDialog.show();
    }

    private void destroyRoom() {
//        EarMonitorInstance monitorInstance = EarMonitorInstance.getInstance();
//        if (monitorInstance.ismEarMonitorOpen()) {
//            EarMonitorInstance.getInstance().updateEarMonitorState(false);
//            mTRTCVoiceRoom.setVoiceEarMonitorEnable(false);
//        }
        mTRTCVoiceRoom.destroyRoom(new TRTCVoiceRoomCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                if (code == 0) {
                    Loog.dTag("VoiceRoomDmActivity", "IM destroy room success");
                    mAppDialog.dismiss();
                    finish();
                } else {
                    Loog.dTag("VoiceRoomDmActivity", "IM destroy room failed:" + msg);
                }
            }
        });

        VoiceRoomManager.getInstance().destroyRoom(mRoomId, new VoiceRoomManager.ActionCallback() {
            @Override
            public void onSuccess() {
                Loog.dTag("VoiceRoomDmActivity", "房间已被销毁");
            }

            @Override
            public void onError(int errorCode, String message) {
                Loog.dTag("VoiceRoomDmActivity", "Error code = " + errorCode + ",msg = " + message);
            }
        });
        mTRTCVoiceRoom.setDelegate(null);
    }

    @SuppressLint("CheckResult")
    public void dissolution() {
        RetrofitHelper.createApi(RoomServer.class).dissolutionRoom(mRoomId).compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        if (baseResponse.getCode() == 1) {
                            destroyRoom();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                    }
                });
    }

    private static class SeatInvitation {
        int seatIndex;
        String inviteUserId;
    }

    //获取DM手册目录
    @SuppressLint("CheckResult")
    public void getDmMenu(String scriptId, String type, String roomSn) {
        RetrofitHelper.createApi(ScriptServer.class).getDmMenu(scriptId, type, roomSn)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ManualMenuResponse>() {
                    @Override
                    public void accept(ManualMenuResponse manualMenuResponse) throws Exception {
                        if (manualMenuResponse.getCode() == 1) {
                            menuData = manualMenuResponse.getData();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                        Loog.dTag("ErrorMsg", "error:" + throwable.getMessage());
                    }
                });
    }

    //获取DM手册目录详情
    @SuppressLint("CheckResult")
    public void getDmMenuDetail(String scriptId, String type, String data, String roomSn) {
        RetrofitHelper.createApi(ScriptServer.class).getDmMenuDetail(scriptId, type, data, roomSn)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DmManualResponse>() {
                    @Override
                    public void accept(DmManualResponse dmManualResponse) throws Exception {
                        if (dmManualResponse.getCode() == 1) {
                            manualList = dmManualResponse.getData();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                        Loog.dTag("ErrorMsg", "error:" + throwable.getMessage());
                    }
                });
    }

    //获取DM手册剧本详情
    @SuppressLint("CheckResult")
    public void getDmScriptDetail(String scriptId, String type, String data, String roomSn) {
        RetrofitHelper.createApi(ScriptServer.class).getDmScriptDetail(scriptId, type, data, roomSn)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DmScriptResponse>() {
                    @Override
                    public void accept(DmScriptResponse dmScriptResponse) throws Exception {
                        if (dmScriptResponse.getCode() == 1) {
                            scriptList = dmScriptResponse.getData();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                        Loog.dTag("ErrorMsg", "error:" + throwable.getMessage());
                    }
                });
    }

    //获取DM手册线索详情
    @SuppressLint("CheckResult")
    public void getDmClueDetail(String scriptId, String type, String data, String roomSn) {
        RetrofitHelper.createApi(ScriptServer.class).getDmClueDetail(scriptId, type, data, roomSn)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DmClueResponse>() {
                    @Override
                    public void accept(DmClueResponse dmClueResponse) throws Exception {
                        if (dmClueResponse.getCode() == 1) {
                            clueList = dmClueResponse.getData();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                        Loog.dTag("ErrorMsg", "error:" + throwable.getMessage());
                    }
                });
    }

    //获取DM手册道具详情
    @SuppressLint("CheckResult")
    public void getDmPropsDetail(String scriptId, String type, String data, String roomSn) {
        RetrofitHelper.createApi(ScriptServer.class).getDmPropsDetail(scriptId, type, data, roomSn)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DmPropsResponse>() {
                    @Override
                    public void accept(DmPropsResponse dmPropsResponse) throws Exception {
                        if (dmPropsResponse.getCode() == 1) {
                            propsList = dmPropsResponse.getData();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                        Loog.dTag("ErrorMsg", "error:" + throwable.getMessage());
                    }
                });
    }

    //获取DM手册地图详情
    @SuppressLint("CheckResult")
    public void getDmMapDetail(String scriptId, String type, String data, String roomSn) {
        RetrofitHelper.createApi(ScriptServer.class).getDmMapDetail(scriptId, type, data, roomSn)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DmMapResponse>() {
                    @Override
                    public void accept(DmMapResponse dmMapResponse) throws Exception {
                        if (dmMapResponse.getCode() == 1) {
                            mapList = dmMapResponse.getData();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                        Loog.dTag("ErrorMsg", "error:" + throwable.getMessage());
                    }
                });
    }

    //获取DM角色剧本
    @SuppressLint("CheckResult")
    public void getDmRoleScript(String scriptId, String type) {
        RetrofitHelper.createApi(ScriptServer.class).getDmRoleScript(scriptId, type)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DmRoleScriptResponse>() {
                    @Override
                    public void accept(DmRoleScriptResponse dmRoleScriptResponse) throws Exception {
                        if (dmRoleScriptResponse.getCode() == 1) {
                            roleScriptData = dmRoleScriptResponse.getData();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                        Loog.dTag("ErrorMsg", "error:" + throwable.getMessage());
                    }
                });
    }

    //DM发送线索
    @SuppressLint("CheckResult")
    public void sendClue(int position, String scriptId, Map<String, Object> pMap, String clueId, String sendType) {
        RetrofitHelper.createApi(ScriptServer.class).sendClue(scriptId, pMap)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        if (baseResponse.getCode() == 1) {
                            sendCustomClueMsg(sendType, position, clueId);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                        Loog.dTag("ErrorMsg", "error:" + throwable.getMessage());
                    }
                });
    }

    //DM发送道具
    @SuppressLint("CheckResult")
    public void sendProp(int position, String scriptId, Map<String, Object> pMap, String propId, String roleName) {
        RetrofitHelper.createApi(ScriptServer.class).sendProp(scriptId, pMap)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        if (baseResponse.getCode() == 1) {
                            sendCustomPropMsg(position, propId, roleName);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                        Loog.dTag("ErrorMsg", "error:" + throwable.getMessage());
                    }
                });
    }

    //DM发送地图
    @SuppressLint("CheckResult")
    public void sendMap(int position, String scriptId, Map<String, Object> pMap, String mapId) {
        RetrofitHelper.createApi(ScriptServer.class).sendMap(scriptId, pMap)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        if (baseResponse.getCode() == 1) {
                            sendCustomMapMsg(position, mapId);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                        Loog.dTag("ErrorMsg", "error:" + throwable.getMessage());
                    }
                });
    }

    //获取情景渲染
    @SuppressLint("CheckResult")
    public void getSceneRender(String scriptId, String type) {
        RetrofitHelper.createApi(ScriptServer.class).getSceneRender(scriptId, type)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<SceneRenderResponse>() {
                    @Override
                    public void accept(SceneRenderResponse sceneRenderResponse) throws Exception {
                        if (sceneRenderResponse.getCode() == 1) {
                            sceneRenderData = sceneRenderResponse.getData();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                        Loog.dTag("ErrorMsg", "error:" + throwable.getMessage());
                    }
                });
    }

    //选取mvp
    @SuppressLint("CheckResult")
    public void chooseMvp(int position, String roleId, Map<String, Object> pMap) {
        RetrofitHelper.createApi(RoomServer.class).chooseMvp(mRoomId, mChooseMvpRequest)
                .compose(this.bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResponse>() {
                    @Override
                    public void accept(BaseResponse baseResponse) throws Exception {
                        if (baseResponse.getCode() == 1) {
                            sendCustomMvpMsg(position, roleId);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Tooast.normalInfo(throwable.getMessage());
                        Loog.dTag("ErrorMsg", "error:" + throwable.getMessage());
                    }
                });
    }

    protected Handler mHandler = new Handler(Looper.getMainLooper());

    private class BGMListener implements TXAudioEffectManager.TXMusicPlayObserver {

        @Override
        public void onStart(int i, int i1) {

        }

        @Override
        public void onPlayProgress(int id, final long curPtsMS, long durationMS) {

        }

        @Override
        public void onComplete(int id, int i1) {
            Log.d("VoiceRoomBaseActivity", "onMusicPlayFinish id " + id);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // 播放完成更新状态
                    mIsPlayEnd = true;
                    replayBgm();
                }
            });
        }
    }

    private void replayBgm() {
        if (mIsPlayEnd) {
            mAudioEffectManager.startPlayMusic(audioMusicParam);
            mIsPlayEnd = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAudioEffectManager != null) {
            mAudioEffectManager.stopPlayMusic(bgmId);
            mAudioEffectManager = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        mIsPlayEnd = false;
        mBGMPlayListenr = null;
    }
}